package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * deviceDataService业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询deviceData
     * 
     * @param id deviceData主键
     * @return deviceData
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询deviceData列表
     * 
     * @param deviceData deviceData
     * @return deviceData
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增deviceData
     * 
     * @param deviceData deviceData
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改deviceData
     * 
     * @param deviceData deviceData
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除deviceData
     * 
     * @param ids 需要删除的deviceData主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除deviceData信息
     * 
     * @param id deviceData主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 基于iot添加设备物模型数据到数据库
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchData(IotMsgNotifyData iotMsgNotifyData) {
        //通过设备id查询设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device==null) {
            throw new BaseException("id为"+deviceId+"的设备不存在");
        }

        //构建设备数据,因为不止一条数据，所以采用foreach
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        List<DeviceData> list=new ArrayList<>();
        services.forEach(s->{
            //先取出时间进行解析
            String eventTime = s.getEventTime();
            LocalDateTime eventime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            s.getProperties().forEach((k,v)->{
                String functionid=k;
                Object datavlue=v;

                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())
                        .iotId(deviceId)
                        .nodeId(device.getNodeId())
                        .nickname(device.getNickname())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(functionid)
                        .accessLocation(device.getBindingLocation())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(String.valueOf(datavlue))
                        .alarmTime(eventime)
                        .build();
                list.add(deviceData);
            });
        });

        //构建完成后，批量保存数据
        if (CollUtil.isNotEmpty(list)) {
            this.saveBatch(list);
        }

        //将最新一次的设备物模型数据存入redis中，以哈希的类型
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LIST_KEY,device.getIotId(), JSONUtil.toJsonStr(list));

    }

    /**
     * 分页查询设备信息
     *
     * @param dto
     * @return
     */
    @Override
    public Page pageList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = lambdaQuery().eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(Page.of(dto.getPageNum(), dto.getPageSize()));
        return page;
    }
}
